<script setup lang="ts">
import { ref, computed, watch } from 'vue';
import { Search } from 'lucide-vue-next';
import { builtinTemplates, templateCategories, getTemplatesByCategory, searchTemplates } from '@/data/prompt-templates';
import type { PromptTemplate } from '@/types';
import { toast } from 'vue-sonner';

interface TemplateSelectorProps {
  open: boolean;
}

const props = defineProps<TemplateSelectorProps>();

const emit = defineEmits<{
  (e: 'update:open', value: boolean): void;
  (e: 'applyTemplate', template: PromptTemplate, mode: 'input' | 'system'): void;
}>();

// 响应式数据
const searchQuery = ref('');
const selectedCategory = ref<string>('all');

// 计算属性
const filteredTemplates = computed(() => {
  let templates = builtinTemplates;

  // 按分类筛选
  if (selectedCategory.value !== 'all') {
    templates = getTemplatesByCategory(selectedCategory.value);
  }

  // 按搜索词筛选
  if (searchQuery.value.trim()) {
    templates = searchTemplates(searchQuery.value);
  }

  return templates;
});

// 方法
function closeDialog() {
  emit('update:open', false);
  // 重置状态
  searchQuery.value = '';
  selectedCategory.value = 'all';
}

function selectCategory(categoryId: string) {
  selectedCategory.value = categoryId;
  searchQuery.value = '';
}

function applyToInput(template: PromptTemplate) {
  emit('applyTemplate', template, 'input');
  toast.success(`已应用模板：${template.name}`);
  closeDialog();
}

function applyAsSystem(template: PromptTemplate) {
  emit('applyTemplate', template, 'system');
  toast.success(`已设置系统提示词：${template.name}`);
  closeDialog();
}

// 监听对话框打开状态
watch(() => props.open, newOpen => {
  if (!newOpen) {
    // 对话框关闭时重置状态
    searchQuery.value = '';
    selectedCategory.value = 'all';
  }
});
</script>

<template>
  <Dialog :open="open" @update:open="closeDialog">
    <DialogContent class="!w-4xl !max-w-4xl max-h-[80vh] flex flex-col">
      <DialogHeader>
        <DialogTitle class="flex items-center gap-2">
          <span class="text-xl">🎯</span>
          选择提示词模板
        </DialogTitle>
        <DialogDescription>
          选择预设的提示词模板，快速开始专业对话
        </DialogDescription>
      </DialogHeader>

      <!-- 搜索框 -->
      <div class="relative mb-4">
        <Search class="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400" />
        <Input
          v-model="searchQuery"
          placeholder="搜索模板..."
          class="pl-10"
        />
      </div>

      <!-- 分类标签 -->
      <div class="flex flex-wrap gap-2 mb-4">
        <Badge
          variant="outline"
          class="cursor-pointer transition-colors"
          :class="{
            'bg-primary text-primary-foreground': selectedCategory === 'all',
          }"
          @click="selectCategory('all')"
        >
          全部
        </Badge>
        <Badge
          v-for="category of templateCategories"
          :key="category.id"
          variant="outline"
          class="cursor-pointer transition-colors"
          :class="{
            [category.color]: selectedCategory === category.id,
            'hover:bg-gray-100 dark:hover:bg-gray-800': selectedCategory !== category.id,
          }"
          @click="selectCategory(category.id)"
        >
          {{ category.name }}
        </Badge>
      </div>

      <!-- 模板列表 -->
      <ScrollArea class="flex-1 pr-4 overflow-y-auto">
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          <Card
            v-for="template of filteredTemplates"
            :key="template.id"
            class="cursor-pointer transition-all duration-200 hover:shadow-md hover:border-primary/50 flex flex-col h-full"
          >
            <CardHeader class="pb-3 flex-shrink-0">
              <div class="flex items-center justify-start gap-2">
                <span class="text-lg">{{ template.icon || '📝' }}</span>
                <div>
                  <CardTitle class="text-sm font-medium">
                    {{ template.name }}
                  </CardTitle>
                </div>
              </div>
              <Badge
                v-if="template.isSystem"
                variant="secondary"
                class="text-xs mt-1"
              >
                系统提示词
              </Badge>

              <CardDescription class="text-xs leading-relaxed line-clamp-3">
                {{ template.description }}
              </CardDescription>
            </CardHeader>

            <!-- 展开的模板内容 -->
            <div class="mx-4 bg-gray-50 dark:bg-gray-900 rounded-md p-3 mb-3">
              <p class="text-xs text-gray-600 dark:text-gray-400 whitespace-pre-wrap">
                {{ template.prompt }}
              </p>
            </div>

            <!-- 操作按钮 -->
            <CardContent class="pt-0 mt-auto flex-shrink-0">
              <div class="flex gap-2">
                <Button
                  size="sm"
                  variant="outline"
                  class="flex-1 text-xs"
                  @click.stop="applyToInput(template)"
                >
                  应用到输入框
                </Button>
                <Button
                  v-if="template.isSystem"
                  size="sm"
                  class="flex-1 text-xs"
                  @click.stop="applyAsSystem(template)"
                >
                  设为系统提示词
                </Button>
              </div>
            </CardContent>
          </Card>
        </div>

        <!-- 空状态 -->
        <div
          v-if="filteredTemplates.length === 0"
          class="text-center py-8 text-gray-500 dark:text-gray-400"
        >
          <span class="text-4xl mb-2 block">🔍</span>
          <p>没有找到匹配的模板</p>
          <p class="text-sm mt-1">
            尝试调整搜索条件或选择其他分类
          </p>
        </div>
      </ScrollArea>

      <!-- 底部提示 -->
      <div class="border-t pt-4 mt-4">
        <p class="text-xs text-gray-500 dark:text-gray-400 text-center">
          💡 提示：点击模板卡片可查看完整内容，双击可快速应用到输入框
        </p>
      </div>
    </DialogContent>
  </Dialog>
</template>

<style scoped>
/* 自定义滚动条样式 */
.scrollbar-thin {
  scrollbar-width: thin;
}

.scrollbar-thin::-webkit-scrollbar {
  width: 6px;
}

.scrollbar-thin::-webkit-scrollbar-track {
  background: transparent;
}

.scrollbar-thin::-webkit-scrollbar-thumb {
  background-color: rgba(156, 163, 175, 0.5);
  border-radius: 3px;
}

.scrollbar-thin::-webkit-scrollbar-thumb:hover {
  background-color: rgba(156, 163, 175, 0.7);
}

/* 文本截断样式 */
.line-clamp-3 {
  display: -webkit-box;
  line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
}
</style>
